﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure.StorageClient;
using System.Diagnostics;
using Microsoft.WindowsAzure;

namespace AzureReader.BLL
{
    public class FeedsQueueManager
    {
        public static void Initialize()
        {
            var account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");


            InitFeedsQueue(account);


        }
           static CloudQueue InitFeedsQueue(CloudStorageAccount account)
        {
            //Create the Queue
            var queueClient = account.CreateCloudQueueClient();
            var queue = queueClient.GetQueueReference("feedsqueue");
            queue.CreateIfNotExist();
            return queue;
        }
        private static CloudQueue GetFeedsQueue()
        {
            var account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            return InitFeedsQueue(account);


        }

        public static void AddFeedToTheQueue(string msg)
        {
            var queue = GetFeedsQueue();


            queue.BeginAddMessage(new CloudQueueMessage(msg), null, null);
        }
        public static bool IsFeedQueueEmpty()
        {
            var queue = GetFeedsQueue();

            if (queue.RetrieveApproximateMessageCount() <= 0)
                return true;
            else
                return false;
            

        }
         

        public static bool IsFeedsQueueEmpty()
        {
            var queue = GetFeedsQueue();
            if (!queue.ApproximateMessageCount.HasValue)
                return true;
            return queue.ApproximateMessageCount.Value > 0 ? false : true;
        }

        public static CloudQueueMessage GetFeedFromQueue()
        {
            var queue = GetFeedsQueue();
            if (queue.Exists())
            {
                var msg = queue.GetMessage();

                if (msg != null)
                {
                    Trace.TraceInformation(string.Format("Feed '{0}' is being dequeued.", msg.AsString));
                    return msg;

                }
            }
            return null;
        }
        public static void DeleteFeedFromQueue(CloudQueueMessage feed)
        {
            var queue = GetFeedsQueue();
            try
            {
                queue.DeleteMessage(feed);
            }
            catch { }

        }
     
    }
}
